package com.etonedu.meals.machine;

import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.android.xhapimanager.XHApiManager;
import com.blankj.utilcode.util.LogUtils;
import com.etonedu.meals.bean.MachineTimeBean;
import com.etonedu.meals.http.LogReportUtils;
import com.etonedu.meals.service.OffOpenService;
import com.etonedu.meals.utils.Utils;

import org.xutils.x;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.Arrays;

public class DeviceUtils {

    /****************************/
    public static void closeMachine(String offTime, String onTime) {
        try {
            XHApiManager apiManager = new XHApiManager();
            apiManager.XHSetPowerOffOnTime(offTime, onTime, true);
            LogUtils.d("关机时间 : "+ offTime+",开机时间 : "+onTime);
            String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
            String pagek = "com.etonedu.general.edu.machine";
            LogReportUtils.log("关机时间 : "+ offTime+",开机时间 : "+onTime,pagek,Utils.getLineInfo(),time1);
        } catch (NoClassDefFoundError e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void clearMachine() {
        try {
            XHApiManager apiManager = new XHApiManager();
            apiManager.XHSetPowerOffOnTime("", "", false);
            LogUtils.d("清除开关机时间");
            String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
            String pagek = "com.etonedu.general.edu.machine";
            LogReportUtils.log("清除开关机时间",pagek,Utils.getLineInfo(),time1);
        } catch (NoClassDefFoundError e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void setMachineScreen(boolean flag) {
        try {
            XHApiManager apiManager = new XHApiManager();
            apiManager.XHOpenOrCloseLCD(flag);
            LogUtils.d("设置开关屏:"+flag);
            String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
            String pagek = "com.etonedu.general.edu.machine";
            LogReportUtils.log("设置开关屏:"+flag,pagek,Utils.getLineInfo(),time1);
        } catch (NoClassDefFoundError e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void closeMachine() {
        try {
            XHApiManager apiManager = new XHApiManager();
            apiManager.XHShutDown();
            LogUtils.d("关机");
            String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
            String pagek = "com.etonedu.general.edu.machine";
            LogReportUtils.log("关机",pagek,Utils.getLineInfo(),time1);
        } catch (NoClassDefFoundError e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void rebootMachine() {
        try {
            XHApiManager apiManager = new XHApiManager();
            apiManager.XHReboot();
            LogUtils.d("重启");
            String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
            String pagek = "com.etonedu.general.edu.machine";
            LogReportUtils.log("重启",pagek,Utils.getLineInfo(),time1);
        } catch (NoClassDefFoundError e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /************全志开关机\开关屏****************/
    public static void setMachineDev(MachineTimeBean om) {
        String model = Build.MODEL;
        if("ZC-83E".equals(model)) {
            Intent intent = new Intent(x.app(), OffOpenService.class);
            intent.putExtra("time",om);
            x.app().startService(intent);

        }
    }

    public static void openMacineScreen() {
        LogUtils.d("开屏");
        Intent intent = new Intent("com.zc.zclcdon");
        x.app().sendBroadcast(intent);
        String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
        String pagek = "com.etonedu.general.edu.machine";
        LogReportUtils.log("开屏",pagek,Utils.getLineInfo(),time1);
    }

    public static void closeMacineScreen() {
        LogUtils.d("关屏");
        Intent intent = new Intent("com.zc.zclcdoff");
        x.app().sendBroadcast(intent);

        String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
        String pagek = "com.etonedu.general.edu.machine";
        LogReportUtils.log("关屏",pagek,Utils.getLineInfo(),time1);
    }
    /***************************/

    // 关机
    public static void shutdown(Context context) {
        LogUtils.d("关机");
        Intent intentShutDown = new Intent("android.intent.action.shutdown");
        context.sendBroadcast(intentShutDown);
        String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
        String pagek = "com.etonedu.general.edu.machine";
        LogReportUtils.log("关机",pagek,Utils.getLineInfo(),time1);
    }

    // 清除开关机时间
    public static void clearMachineTime(Context context) {
        LogUtils.d("清除开关机时间");
        Intent intentShutDown = new Intent("android.intent.ClearOnOffTime");
        context.sendBroadcast(intentShutDown);

        String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
        String pagek = "com.etonedu.general.edu.machine";
        LogReportUtils.log("清除开关机时间",pagek,Utils.getLineInfo(),time1);
    }

    public static void sendCode(final int keyCode) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Instrumentation ins = new Instrumentation();
                    ins.sendKeyDownUpSync(keyCode);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    // 重启
    public static void reboot(Context context) {
        Intent intentReboot = new Intent("android.intent.action.reboot");
        context.sendBroadcast(intentReboot);
        LogUtils.d("重启");
        String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
        String pagek = "com.etonedu.general.edu.machine";
        LogReportUtils.log("重启",pagek,Utils.getLineInfo(),time1);
    }

    // 设置开关机时间
    public static void setOnOffMachineV2(MachineTimeBean om) {

        LogUtils.d("关机时间 : "+ om.getOffDate()+",开机时间 : "+om.getOnDate());
        String[] starts = null;
        if (!TextUtils.isEmpty(om.getOnDate())) {
            starts = om.getOnDate().split("-");
        }
        String[] ends = null;
        if (!TextUtils.isEmpty(om.getOffDate())) {
            ends = om.getOffDate().split("-");
        }

        int[] intstarts = new int[starts.length];
        int[] intsends = new int[ends.length];

        for (int i = 0; i < starts.length; i++) {
            intstarts[i] = Integer.valueOf(starts[i]);
        }

        for (int i = 0; i < ends.length; i++) {
            intsends[i] = Integer.valueOf(ends[i]);
        }

        String content = "开机时间 = "+ Arrays.toString(intstarts) + ",关机时间 = "+ Arrays.toString(intsends);

        LogUtils.d(content);
        timerSwitch(x.app(), intstarts, intsends);

        String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
        String pagek = "com.etonedu.general.edu.machine";
        LogReportUtils.log("设置开关机时间:"+content,pagek,Utils.getLineInfo(),time1);
    }

    // 定时开关机
    public static void timerSwitch(Context contexts, int[] timeonArray, int[] timeoffArray) {
        timerSwitch(contexts,timeonArray,timeoffArray,true);
    }

    public static void timerSwitch(Context contexts, int[] timeonArray, int[] timeoffArray, boolean enable) {
        Intent intent = new Intent("android.intent.action.setpoweronoff");
//        Intent intent = new Intent("android.56iq.intent.action.setpoweronoff");
        intent.putExtra("timeon", timeonArray);
        intent.putExtra("timeoff", timeoffArray);
        intent.putExtra("enable", enable); //使能开关机功能，设为false,则为关闭
        contexts.sendOrderedBroadcast(intent,null);
    }

    // 定时开屏
    public static int timerSwitchOnScreen() {
        LogUtils.d("开屏");
        int result = 0;
        try {
            result = writeFile("1");
        } catch (Exception e) {
            e.printStackTrace();
        }

        String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
        String pagek = "com.etonedu.general.edu.machine";
        LogReportUtils.log("开屏",pagek,Utils.getLineInfo(),time1);

        return result;
    }

    // 定时关屏
    public static int timerSwitchOffScreen() {
        LogUtils.d("关屏");
        int result = 0;
        try {
            result = writeFile("0");
        } catch (Exception e) {
            e.printStackTrace();
        }

        String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
        String pagek = "com.etonedu.general.edu.machine";
        LogReportUtils.log("关屏",pagek,Utils.getLineInfo(),time1);
        return result;
    }
    // 定时关屏
    public static void timerSwitchOffScreenAndroid5() {
        LogUtils.d("关屏");
        try {
            String model = Build.MODEL;
            if ("rk3288_box".equals(model)) {
                writeFileAndroid5For3288("0");
            } else {
                writeFileAndroid5("0");
            }

            String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
            String pagek = "com.etonedu.general.edu.machine";
            LogReportUtils.log("关屏",pagek,Utils.getLineInfo(),time1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 定时开屏
    public static void timerSwitchOnScreenAndroid5() {
        LogUtils.d("开屏");
        try {
            String model = Build.MODEL;;
            if ("rk3288_box".equals(model)) {
                writeFileAndroid5For3288("1");
            } else {
                writeFileAndroid5("1");
            }

            String time1 = Utils.timestamp2String1(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss");
            String pagek = "com.etonedu.general.edu.machine";
            LogReportUtils.log("开屏",pagek,Utils.getLineInfo(),time1);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 写文件
    public static int writeFile(String str) throws IOException, InterruptedException {

        File file = new File("/sys/class/disp/disp/attr/sys");
        file.setExecutable(true);
        file.setReadable(true);//设置可读权限
        file.setWritable(true);//设置可写权限
        if (str.equals("0")) {
            do_exec("busybox echo 0 > /sys/class/disp/disp/attr/sys");
        }  else {
            do_exec("busybox echo 1 > /sys/class/disp/disp/attr/sys");
        }
        String result = readFile(file);
        Log.d("writeFile","str = "+str+",result = "+result);
        if (str.equals(result)) {// 1、成功 0、失败
            return 1;
        } else {
            return 0;
        }
    }

    public static String readFile(File file) {
        String result = "";
        try {
            if (file != null && file.exists()) {
                FileInputStream fis = new FileInputStream(file);
                BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
                result = reader.readLine();
                fis.close();
                Log.d("readFile","result = "+result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void writeFileAndroid5(String content) {
        File file = new File("/sys/devices/fb.11/graphics/fb0/pwr_bl");
        file.setExecutable(true);
        file.setReadable(true);//设置可读权限
        file.setWritable(true);//设置可写权限

        if ("0".equals(content)) {
            do_exec("echo 0 > /sys/devices/fb.11/graphics/fb0/pwr_bl");

        } else {
            do_exec("echo 1 > /sys/devices/fb.11/graphics/fb0/pwr_bl");
        }
    }

    public static void writeFileAndroid5For3288(String content) {
        File file = new File("/sys/devices/fb.8/graphics/fb0/pwr_bl");
        file.setExecutable(true);
        file.setReadable(true);//设置可读权限
        file.setWritable(true);//设置可写权限

        if ("0".equals(content)) {
            do_exec("echo 0 > /sys/devices/fb.8/graphics/fb0/pwr_bl");

        } else {
            do_exec("echo 1 > /sys/devices/fb.8/graphics/fb0/pwr_bl");
        }
    }

    public static String do_exec(String cmd) {
        try {
            /* Missing read/write permission, trying to chmod the file */
            Process su;
            su = Runtime.getRuntime().exec("su");
            String str = cmd + "\n" + "exit\n";
            su.getOutputStream().write(str.getBytes());

            BufferedReader successResult = new BufferedReader(new InputStreamReader(su.getInputStream()));
            BufferedReader errorResult = new BufferedReader(new InputStreamReader(su.getErrorStream()));

            String s;
            StringBuilder successMsg = new StringBuilder();
            StringBuilder errorMsg = new StringBuilder();
            while ((s = successResult.readLine()) != null) {
                successMsg.append(s);
            }
//            Log.d("do_exec","successMsg = "+successMsg);
            while ((s = errorResult.readLine()) != null) {
                errorMsg.append(s);
            }
//            Log.d("do_exec","errorMsg = "+errorMsg);

            if ((su.waitFor() != 0)) {
//                Log.d("do_exec","cmd=" + cmd + " error!");
//                throw new SecurityException();
            }
            return successMsg.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String getPowerOnOffTime() {
        return getValueFromProp("persist.sys.poweronoff");
    }

    public static String getPowerCurrTime() {
        return getValueFromProp("persist.sys.powercurofftime");
    }

    public static String getNewPowerOnTime() {
        return getValueFromProp("persist.sys.powerontime");
    }

    public static String getNewPowerOffTime() {
        return getValueFromProp("persist.sys.powerofftime");
    }

    public String getLastestPowerOnTime() {
        return getValueFromProp("persist.sys.poweronoffbak");
    }

    public static String getValueFromProp(String key) {
        String value = "";
        try {
            Class classType = Class.forName("android.os.SystemProperties");
            Method getMethod = classType.getDeclaredMethod("get", String.class);
            value = (String) getMethod.invoke(classType, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }
}
